package com.imooc.imoocbilibili.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imooc.imoocbilibili.constants.AuthRoleConstant;
import com.imooc.imoocbilibili.entity.User;
import com.imooc.imoocbilibili.entity.UserMoments;
import com.imooc.imoocbilibili.entity.UserRole;
import com.imooc.imoocbilibili.interceptor.ThreadUser;
import com.imooc.imoocbilibili.service.UserRoleService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据权限控制
 */
@Order(1)
@Component
@Aspect
public class DataLimitedAspect {

    @Autowired
    private UserRoleService userRoleService;

    @Pointcut("@annotation(com.imooc.imoocbilibili.annotation.DataLimited)")
    public void check(){
    }

    @Before("check()")
    public void doBefore(JoinPoint joinPoint){
        User user = ThreadUser.getUser();
        Long userId = user.getId();
        List<UserRole> userRoles = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserid, userId));

        Set<String> roleCodeSet = userRoles.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        Object[] args = joinPoint.getArgs();
        for(Object arg : args){
          if(arg instanceof UserMoments){
              UserMoments userMoment = (UserMoments)arg;
              String type = userMoment.getType();
              // 限制角色是lv1的用户, type字段只能传0
              if(roleCodeSet.contains(AuthRoleConstant.ROLE_LV1) && !"0".equals(type)){
                  throw new RuntimeException("参数异常");
              }
          }
        }
    }
}
